package hehe.web;

import hehe.He;
import hehe.core.base.Application;
import hehe.core.base.Response;
import hehe.router.Controller;
import hehe.router.Router;
import hehe.router.Url;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * http 请求应用控制器
 *<B>说明：</B>
 *<pre>
 * 略
 *</pre>
 *<B>示例：</B>
 *<pre>
 *  略
 *</pre>
 *<B>日志：</B>
 *<pre>
 *  略
 *</pre>
 *<B>注意事项：</B>
 *<pre>
 *  略
 *</pre>
 */
public class WebApplication extends Application
{

    @Override
    protected void run(HttpServletRequest req, HttpServletResponse resp) throws Exception
    {
        // 路由规则
        Url url = He.getBean("router");
        Map<String,String> rule = new HashMap<String,String>(){{
            put("pathinfoRule","<controller:\\\\w+>/<action:\\\\w+>");
            put("urlRule","<controller>/<action>");
        }};

        url.addRule(rule);
        Controller urlController = url.findController(req.getRequestURI(),req.getMethod().toUpperCase());
        String controllerName = urlController.getController();
        String actionName = urlController.getAction();

        try {
            Object controller = this.createController(controllerName);
            Object result = this.runAction(controller,actionName,req);

            if (result instanceof Response) {
                ((Response) result).send();
            } else {
                WebResponse webResponse = new WebResponse(resp);
                long endTime = System.currentTimeMillis();
                webResponse.setContent((String)result +  "time:" + (endTime - this.starttime)).send();
            }

        } catch (Exception e) {
            // 产生异常
            e.printStackTrace();
        }
    }
}
